<template>
  <el-dialog :before-close="handleClosed" title="镜像版本比较" v-model="visibleRef" :width="table_width">
    <el-tabs v-model="tabs_value">
      <el-tab-pane label="镜像" name="mirror">
    <el-row>
      <el-button type="success" @click="start_compare_image_version">比较</el-button>
      <el-button type="warning" @click="update_image_version">升级</el-button>
      <el-button type="primary" @click="drawer = true">导出镜像</el-button>
    </el-row>
    <el-row>
      <el-select v-model="now_version_pod_select_value" class="m-2" placeholder="新版本环境"
        @change="now_version_pod_select_value_click">
        <el-option v-for="item in cluster_select_data" :key="item.kubernetes_cluster_id"
          :label="item.kubernetes_cluster_name" :value="item.kubernetes_cluster_id" />
      </el-select>
      <el-select v-model="now_version_cluster_select_value" filterable class="m-2" placeholder="新版本空间">
        <el-option v-for="item in now_cluster_select_data" :key="item.name" :label="item.name" :value="item.name" />
      </el-select>
      <ArrowRight style="width: 1em; height: 1em; margin-right: 8px; margin-left: 8px; margin-top: 8px " />
      <el-select v-model="old_version_pod_select_value" class="m-2" placeholder="旧版本环境"
        @change="old_version_pod_select_value_click">
        <el-option v-for="item in cluster_select_data" :key="item.kubernetes_cluster_id"
          :label="item.kubernetes_cluster_name" :value="item.kubernetes_cluster_id" />
      </el-select>
      <el-select v-model="old_version_cluster_select_value" class="m-2" filterable placeholder="旧版本空间">
        <el-option v-for="item in old_cluster_select_data" :key="item.name" :label="item.name" :value="item.name">
        </el-option>
      </el-select>
    </el-row>
  </el-tab-pane>
  </el-tabs>
    <el-drawer v-model="drawer" title="导出进度" size="15%" :append-to-body="true">
      <el-row>
        <el-col :span="12">
          <el-switch size="large" v-model="if_difference" class="ml-2" active-text="勾选差异打包" inactive-text="勾选全部打包"
            inline-prompt
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #409EFF; height: 32px; padding-bottom: 1px;" />
        </el-col>
        <el-col :span="12">
          <el-switch size="large" v-model="if_target_location" class="ml-2" active-text="下载包到本机系统"
            inactive-text="下载包到目标环境" inline-prompt @change="if_target_location_change"
            style="--el-switch-on-color: #13ce66; --el-switch-off-color: #409EFF; height: 32px; padding-bottom: 1px;" />
        </el-col>
      </el-row>
      <el-row>
        <el-button-group>
          <el-button plain type="primary" @click="download_image" round>开始</el-button>
          <el-button type="danger" icon="CloseBold" @click="download_image_close" round />
        </el-button-group>
      </el-row>
      <div style="height: 300px">
        <el-steps direction="vertical" :active="active" :process-status="active_process_status_" finish-status="success">
          <el-step title="处理信息" description="结构标记服务器打包指令" icon="Edit" />
          <el-step title="下载镜像" description="正在下载镜像到标记服务器" icon="Switch" />
          <el-step title="正在打包" description="标记服务器tmp下生成打包文件" icon="Box" />
          <el-step title="开始复制" description="拷贝文件到平台" icon="Promotion" />
          <el-step title="开始下载" :description="target_location_description" icon="Download" />
        </el-steps>
      </div>
      <el-progress :text-inside="true" :stroke-width="24" :percentage="dwon_percentage" status="success" />
    </el-drawer>

    <div style="width: 100%; height: 500px">
      <el-auto-resizer>
        <template #default="{ height, width }">
          <el-table-v2 :columns="columns" :data="table_data" :height="height" :width="width" :estimated-row-height="50"
            style="font-size: 10px" :expand-column-key="columns[0].key">
            <template #row="props">
              <Row v-bind="props" />
            </template>
          </el-table-v2>
        </template>
      </el-auto-resizer>
    </div>

  </el-dialog>
</template>

<script lang="tsx" setup>
import { ref, watch, watchEffect, unref, onMounted, FunctionalComponent } from "vue";
import * as Request from "@/general/request";
import {
  ElCheckbox,
  ElMessage,
  CheckboxValueType
} from "element-plus";
import { server_config } from "@/service_config";

let tabs_value = ref("mirror")
const visibleRef = ref(false);
const cluster_select_data: any = ref([]);
const old_cluster_select_data: any = ref([]);
const now_cluster_select_data: any = ref([]);
const now_version_cluster_select_value = ref("");
const old_version_cluster_select_value = ref("");
const now_version_pod_select_value = ref("");
const old_version_pod_select_value = ref("");
const table_data: any = ref([]);
const drawer = ref(false)
let active = ref(0)
let active_process_status_ = ref("process")
const if_difference = ref(true)
let if_target_location = ref(true)
let target_location_description = ref("下载文件到本地")
const wsuri = server_config["background_ws"] + "/download_event";
let ws: any = null
let websocketsend_cron: any = ref(null);
let dwon_percentage = ref(0)



const props = defineProps({
  visible: {
    type: Boolean,
    default: false,
  },
});

const emit = defineEmits(["closed", "update:visible"]);

watch(
  () => unref(visibleRef),
  (v) => {
    emit("update:visible", v);
  },
  {
    immediate: false,
  }
);

watchEffect(() => {
  visibleRef.value = !!props.visible;
});

function handleClosed() {
  visibleRef.value = false;
  emit("closed", false);
}

const table_width = 1200;

// 表格定义
const columns = [
  {
    key: "now_version_pod_name",
    dataKey: "now_version_pod_name", //需要渲染当前列的数据字段，
    title: "deployment名称", //显示在单元格表头的文本
    width: table_width / 6, //当前列的宽度，必须设置
    fixed: true, //是否固定列
  },
  {
    key: "now_version_pod_image",
    dataKey: "now_version_pod_image",
    title: "新版本pod镜像",
    width: table_width / 5,
    fixed: true,
  },
  //   {
  //   key: "old_version_pod_name",
  //   dataKey: "old_version_pod_name",
  //   title: "旧版本pod名称",
  //   width: table_width / 6,
  //   fixed: true
  // },
  {
    key: "old_version_pod_image",
    dataKey: "old_version_pod_image",
    title: "旧版本pod镜像",
    width: table_width / 5,
    fixed: true,
  },
  {
    key: "tar_version_pod_image",
    dataKey: "tar_version_pod_image",
    title: "预打包镜像",
    width: table_width / 3,
  },
];

table_data.value = [];

const now_version_pod_select_value_click = () => {
  get_env_k8s_interspace(now_version_pod_select_value, "now");
};

const old_version_pod_select_value_click = () => {
  get_env_k8s_interspace(old_version_pod_select_value, "old");
};

const if_target_location_change = (val: boolean) => {
  if (val) {
    target_location_description.value = "下载包到本机"
  } else {
    target_location_description.value = "下载包到旧版本环境标记服务器tmp下"
  }
}

// 获取勾选的条目
const get_select_items = () => {
  const table_data_: Array<object> = []
  table_data.value.map((row: any) => {
    if (Reflect.has(row, "checked") && row.checked) {
      table_data_.push(row)
    }
  })
  return table_data_
}

// 查询集群
const get_cluster = async () => {
  const response = await Request.GET(
    "/background/home/kubernetes/env_k8s_cluster"
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      cluster_select_data.value = return_data.data;
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 查询空间下拉选择
const get_env_k8s_interspace = async (kubernetes_cluster_id: any, old_or_now: any) => {
  const response = await Request.GET("/background/home/kubernetes/namespace", {
    kubernetes_cluster_id: kubernetes_cluster_id.value,
  });
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      if (old_or_now === "old") {
        old_cluster_select_data.value = return_data.data;
      } else {
        now_cluster_select_data.value = return_data.data;
      }
      // ElMessage.success(return_data.msg)
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 版本比较
const start_compare_image_version = async () => {
  const response = await Request.GET(
    "/background/home/kubernetes/compare_image_version",
    {
      now_kubernetes_cluster_id: now_version_pod_select_value.value,
      old_kubernetes_cluster_id: old_version_pod_select_value.value,
      now_version_cluster_select_name: now_version_cluster_select_value.value,
      old_version_cluster_select_name: old_version_cluster_select_value.value,
    }
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      table_data.value = return_data.data;
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 升级勾选项版本
const update_image_version = async () => {

  const check_data = get_select_items()

  const response = await Request.PUT(
    "/background/home/kubernetes/update_image_version", {
    "old_kubernetes_cluster_id": old_version_pod_select_value.value,
    "old_version_cluster_select_value": old_version_cluster_select_value.value,
    "data": check_data
  }
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      ElMessage.success(return_data.msg);
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

onMounted(get_cluster);

// 表格行下拉选择
const Row = ({ cells, rowData }: any) => {
  if (rowData.is_children) {
    return (
      <el-row>
        <el-col span={12}>
          <el-timeline style="padding-top: 20px; width: 150px">
            <el-timeline-item color={"#67C23A"}>
              {rowData.old_pod_image_version}
            </el-timeline-item>
            <el-timeline-item color={"#E6A23C"}>
              {rowData.now_pod_image_version}
            </el-timeline-item>
          </el-timeline>
        </el-col>
        <el-col span={12}>
          <el-timeline style="padding-top: 20px; width: 300px">
            <el-timeline-item color={"#67C23A"}>
              {rowData.old_image_repository}
            </el-timeline-item>
            <el-timeline-item color={"#E6A23C"}>
              {rowData.now_image_repository}
            </el-timeline-item>
          </el-timeline>
        </el-col>
      </el-row>
    );
  }
  return cells;
};

Row.inheritAttrs = false;

type SelectionCellProps = {
  value: boolean
  intermediate?: boolean
  onChange: (value: CheckboxValueType) => void
}

const SelectionCell: FunctionalComponent<SelectionCellProps> = ({
  value,
  intermediate = false,
  onChange,
}) => {
  return (
    <ElCheckbox
      onChange={onChange}
      modelValue={value}
      indeterminate={intermediate}
    />
  )
}

columns.unshift({
  key: 'selection',
  width: 50,
  cellRenderer: ({ rowData }: any) => {
    const onChange = (value: CheckboxValueType) => (
      rowData.checked = value
    )
    return <SelectionCell value={rowData.checked} onChange={onChange} />
  },

  headerCellRenderer: () => {
    const _data = unref(table_data)
    const onChange = (value: CheckboxValueType) =>
    (table_data.value = _data.map((row: any) => {
      row.checked = value
      return row
    }))
    const allSelected = _data.every((row: any) => row.checked)
    const containsChecked = _data.some((row: any) => row.checked)

    return (
      <SelectionCell
        value={allSelected}
        intermediate={containsChecked && !allSelected}
        onChange={onChange}
      />
    )
  },
})

// 开始下载镜像
const download_image = async () => {

  dwon_percentage.value = 0
  active.value = 0

  const check_data = get_select_items()

  const response = await Request.POST(
    "/background/home/kubernetes/download_image", {
    "now_kubernetes_cluster_id": now_version_pod_select_value.value,
    "old_kubernetes_cluster_id": old_version_pod_select_value.value,
    "now_version_cluster_select_value": now_version_cluster_select_value.value,
    "data": check_data,
    "if_difference": if_difference.value,
    "if_target_location": if_target_location.value
  }
  );
  if (response && response.data) {
    var return_data = response.data;
    if (return_data.success) {
      get_download_image(return_data.data)
      ElMessage.success(return_data.msg);
    } else {
      ElMessage.error(return_data.msg);
    }
  }
};

// 下载文件到客户端
const get_file = (download_info: any) => {
  ElMessage.success("开始下载文件到本地");
  active.value = active.value + 1
  Request.DOWNLOADFILE(
    "/background/home/down_file/tmp_file_down",
    {
      file_type: download_info.file_type,
      file_name: download_info.file_name,
    },
    { fileName: download_info.file_name },
    callback
  );
  active_process_status_.value = "success"
};

const callback = (progressEvent: any) => {
  dwon_percentage.value = Math.floor(progressEvent.loaded / progressEvent.total * 100)//实时获取上传进度 
}

// 开始获取下载信息
const get_download_image = async (download_event_ids: string) => {
  ws = new WebSocket(wsuri);

  let submit_info = {
    download_event_ids: download_event_ids,
    download_event_type: "normal_info"
  }

  let submitCode = JSON.stringify(submit_info)

  ws.onopen = function () {
    websocketsend_cron.value = setInterval(() => {
      ws.send(submitCode);
    }, 10000);
  }

  ws.onmessage = function (e: any) {
    const datas = JSON.parse(e.data);
    if (datas.success) {
      if (datas.data) {
        // 下载步骤
        active.value = Number(datas.data[0].download_enent_step_code)
        // active_process_status.value = "error"
        // 下载当前步骤状态
        // debugger
        // console.log('11',datas.data) 

        switch (datas.data[0].download_event_status) {
          case '0':
            active_process_status_.value = "error"
            break;
          case '1':
            active_process_status_.value = "success"
            break;
          case '3':
            active_process_status_.value = "success"
            submit_info.download_event_type = "platform_file_save_info"
            submitCode = JSON.stringify(submit_info)
            break;
          case '4':
            const download_event_info = JSON.parse(datas.data[0].download_event_info)
            if (if_target_location.value) {
              download_image_close()
              get_file(download_event_info)
            } else {
              dwon_percentage.value = parseInt(download_event_info.percents)
              if (dwon_percentage.value == 100){
                ElMessage.success("传输成功,获取信息关闭.")
                download_image_close()
              }
            }
            break;
          default:
            active_process_status_.value = "process"  // wait / process / finish / error / success
            break;
        }
        // console.log('22', active_process_status_.value)
      }
    }
    else {
      download_image_close()
      ElMessage.error(datas.msg)
    }
  }

  ws.onerror = function () {
    debugger
    ElMessage.error("镜像下载进度获取失败，连接断开!")
    clearInterval(websocketsend_cron.value);
  }

  ws.onclose = function () {
    ElMessage.warning("信息获取连接断开!")
    clearInterval(websocketsend_cron.value);
  }
}

const download_image_close = async () => {
  ws.close();
}

</script>

<style>
.el-row {
  margin-bottom: 5px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.el-table-v2__row-depth-0 {
  height: 20px;
}

.el-table-v2__cell-text {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
